package com.wty.app.bthcar;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.BLUETOOTH;
import static android.Manifest.permission.BLUETOOTH_ADMIN;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.wty.app.bthcar.adapter.DeviceDialog;
import com.wty.app.bthcar.adapter.SetRateDialog;
import com.wty.app.bthcar.adapter.SetXRateDialog;
import com.wty.app.bthcar.bluetooth.BluetoothBLEChatService;
import com.wty.app.bthcar.bluetooth.BluetoothChatService;
import com.wty.app.bthcar.bluetooth.DeviceListActivity;
import com.wty.app.bthcar.info.DataBean;
import com.wty.app.bthcar.info.DeviceBean;
import com.wty.app.bthcar.utils.PreferenceUtil;
import com.wty.app.bthcar.utils.RepeatingTask;
import com.wty.app.bthcar.view.DialProgress;
import com.wty.app.bthcar.view.PlaneControlView;

import java.text.MessageFormat;

import io.reactivex.rxjava3.functions.Consumer;

public class HavorBoardBLEControlActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothChatService mChatService = null;
    private String mConnectedDeviceName = null;
    public static  byte[] revDataForCharacteristic;
    int mState = 1;
    private int xRange = 0;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override // android.os.Handler
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    switch (msg.arg1) {
                        case 2:
                            Toast.makeText(HavorBoardBLEControlActivity.this.getApplicationContext(), "正在连接该蓝牙设备", Toast.LENGTH_SHORT).show();
                            bltStatus.setSelected(false);
                            bltStatus.setText(MessageFormat.format("蓝牙：正在连接", msg.getData().getString(BluetoothChatService.DEVICE_NAME)));
                            return;
                        case 3:
                        default:
                            return;
                    }
                case 2:
                    new String((byte[]) msg.obj, 0, msg.arg1);
                    return;
                case 3:
                    String writeMessage = new String((byte[]) msg.obj);
                    String result = "";
                    if (writeMessage.equals(PreferenceUtil.getInstance().getStopCode())) {
                        result = "停车";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getLeftCode())) {
                        result = "左转";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getRightCode())) {
                        result = "右转";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getUpCode())) {
                        result = "前进";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getDownCode())) {
                        result = "后退";
                    }
                    Log.d("蓝牙小车:", result);
                    return;
                case 4:
                    HavorBoardBLEControlActivity.this.mConnectedDeviceName = msg.getData().getString(BluetoothChatService.DEVICE_NAME);
                    Toast.makeText(HavorBoardBLEControlActivity.this.getApplicationContext(), "连接上 " + HavorBoardBLEControlActivity.this.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    bltStatus.setSelected(true);
                    bltStatus.setText(MessageFormat.format("蓝牙已连接:{0}", HavorBoardBLEControlActivity.this.mConnectedDeviceName));
                    return;
                case 5:
                    Toast.makeText(HavorBoardBLEControlActivity.this.getApplicationContext(), msg.getData().getString(BluetoothChatService.TOAST), Toast.LENGTH_SHORT).show();
                    return;
                default:
                    return;
            }
        }
    };




    private PlaneControlView recLeft;
    private PlaneControlView recRight;
    private TextView bltStatus;
    private TextView rightRate;
    private TextView leftRate;
    private DataBean bean;
    private DialProgress centerProgress;
    private int speedRange=0;
    private int speedXRange=0;
    private RepeatingTask task;
    private int blueType;
    private String deviceName;
//    private boolean connectedStatu;
    private BluetoothBLEChatService bluetoothBLEChatService;

    @SuppressLint("CheckResult")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(getResources().getColor(R.color.theme_dark));
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                , WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_hoverboard_layout);
        initPermissions();
        speedRange = PreferenceUtil.getInstance().getSpeedRate();
        speedXRange = PreferenceUtil.getInstance().getXSpeedRate();
        xRange = PreferenceUtil.getInstance().getXSpeedRate();
        bltStatus = findViewById(R.id.blt_state);
        centerProgress = findViewById(R.id.circle_progress);
        rightRate = findViewById(R.id.right_rate);
        leftRate = findViewById(R.id.left_rate);
        recLeft = findViewById(R.id.rockerView_left);
        recRight = findViewById(R.id.speed);
        TextView btnL1 = findViewById(R.id.btn_left1);
        TextView btnL2 = findViewById(R.id.btn_left2);
        bean = new DataBean();

        TextView stopBtn = findViewById(R.id.stop_btn);
        stopBtn.setOnClickListener(v -> {
            sendMessage("{\"L\":\"0\",\"R\":\"0\",\"S\":1}");
        });
        TextView offBtn = findViewById(R.id.off_btn);
        offBtn.setOnClickListener(v ->{
                mState = 128;
                updateSpeedMsg();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                      mState = 1;
                    }
                },3000);
//                sendMessage("{\"L\":\"0\",\"R\":\"0\",\"S\":128}");
            }
        );
        btnL1.setOnClickListener(v -> new XPopup.Builder(v.getContext()).isViewMode(true).hasBlurBg(false).animationDuration(200).hasShadowBg(false).asCustom(new SetRateDialog(v.getContext(), new SetRateDialog.OnItemChangeListener() {
            @Override
            public void OnResult(int value) {
                speedRange = value;
            }
        })).show());
        btnL2.setOnClickListener(v -> new XPopup.Builder(v.getContext()).isViewMode(true).hasBlurBg(false).animationDuration(200).hasShadowBg(false).asCustom(new SetXRateDialog(v.getContext(), new SetXRateDialog.OnItemChangeListener() {
            @Override
            public void OnResult(int value) {
                speedXRange = value;
            }
        })).show());
        initListener();
        this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (this.mBluetoothAdapter == null) {
            Toast.makeText(this, "手机无蓝牙设备", Toast.LENGTH_SHORT).show();
        } else if (this.mBluetoothAdapter.isEnabled()) {
            this.mChatService = new BluetoothChatService(this, this.mHandler);
        } else if (Build.VERSION.SDK_INT >= 23) {
            RxPermissions rxPermissions = new RxPermissions(this);

            rxPermissions.request(BLUETOOTH,BLUETOOTH_ADMIN,ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Throwable {
                    if (aBoolean) {
                        HavorBoardBLEControlActivity.this.startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 2);
                    }
                }
            });
        } else {
            startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 2);
        }

        task = new RepeatingTask(100, new RepeatingTask.OnSendListener() {
            @Override
            public void OnSend() {
                updateSpeedMsg();
            }
        });
        task.start();
    }

    /* access modifiers changed from: protected */
    @Override // android.support.v4.app.FragmentActivity, android.app.Activity
    public void onResume() {
        super.onResume();
        if (this.mChatService != null && this.mBluetoothAdapter != null && this.mBluetoothAdapter.isEnabled() && this.mChatService.getState() == 0) {
            this.mChatService.start();
        }
    }

    @Override // android.support.v7.app.AppCompatActivity, android.support.v4.app.FragmentActivity, android.app.Activity
    public void onDestroy() {
        super.onDestroy();
        if (this.mChatService != null) {
            this.mChatService.stop();
        }
        if (this.mBluetoothAdapter != null && this.mBluetoothAdapter.isEnabled()) {
            this.mBluetoothAdapter.disable();
        }
        if (task!=null){
            task.stop();
        }
        if (bluetoothBLEChatService!=null){
            bluetoothBLEChatService.onStopSend();
        }
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == -1) {
                    BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS));
                    if (this.mChatService == null) {
                        this.mChatService = new BluetoothChatService(this, this.mHandler);
                        this.mChatService.start();
                    }
                    this.mChatService.connect(device);
                    return;
                }
                return;
            case 2:
                if (resultCode == -1) {
                    Toast.makeText(this, (int) R.string.bt_enabled_success, Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, (int) R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
                return;
            default:
                return;
        }
    }

    public double  mapValue(float x,float y) {
        int rangX = (int) (x * speedRange);
        int rangY = (int) (y * speedRange);
        // 使用勾股定理计算斜边的长度
        double offset = Math.sqrt(Math.pow(Math.abs(rangX), 2) + Math.pow(Math.abs(rangY), 2));
        // 返回计算结果
        return offset;
    }
    public int getDirectionMap(float x){
        int directX = (int) (x * xRange);
        return directX;
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        recLeft.setControlMode(PlaneControlView.CONTROL_BY_TOUCH);
        recRight.setControlMode(PlaneControlView.CONTROL_BY_TOUCH);
        recLeft.setOnLocaListener(new PlaneControlView.OnLocaListener() {
            @Override
            public void getLocation(float x, float y) {
                Log.e("getPrintXY",x+"==="+y);
                int mapValue = (int) mapValue(x,y);
                int iLeft = mapValue;
                int iRight = mapValue;

                double c = Math.sqrt((double) ((x * x) + (y * y)));
                if (c > 1.0d) {
                    c = 1.0d;
                }
                int lrspeed = (int) (((double) speedRange) * c);
                double angle = Math.atan2((double) x, (double) y) / 1.5707963267948966d;
                if (angle < -1.0d) {
                    iRight = -lrspeed;
                    iLeft = (int) (((double) (-lrspeed)) * Math.abs(1.0d + angle));
                } else if (angle < 0.0d) {
                    iRight = lrspeed;
                    iLeft = (int) (((double) lrspeed) * (1.0d - Math.abs(angle)));
                } else if (angle < 1.0d) {
                    iRight = (int) (((double) lrspeed) * (1.0d - Math.abs(angle)));
                    iLeft = lrspeed;
                } else {
                    iRight = (int) (((double) (-lrspeed)) * Math.abs(angle - 1.0d));
                    iLeft = -lrspeed;
                }
                //保持直行，容错
                if (Math.abs(getDirectionMap(x))<30){
                    iLeft = iRight;
                }

                bean.setS(mState);
                bean.setL(iRight);
                bean.setR(iLeft);
                updateSpeedMsg();
            }
        });
        recRight.setOnLocaListener((x, y) -> {


        });

        bltStatus.setOnClickListener(v -> {
            new XPopup.Builder(v.getContext()).isViewMode(true).hasBlurBg(false).animationDuration(200).hasShadowBg(false).asCustom(new DeviceDialog(v.getContext(), itemListener)).show();
        });
    }


    DeviceDialog.OnItemListener itemListener = new DeviceDialog.OnItemListener() {
        @Override
        public void OnResult(DeviceBean deviceBean) {
           /* blueType = deviceBean.getType();
            if (deviceBean.getType() == 1){

            }
            if (deviceBean.getType()==3 || deviceBean.getType()==2){
                bluetoothBLEChatService = new BluetoothBLEChatService(deviceBean,statusListener);
                bluetoothBLEChatService.init(HavorBoardControlActivity.this);

            }*/
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceBean.getDeviceMac());
            if (mChatService == null) {
                mChatService = new BluetoothChatService(HavorBoardBLEControlActivity.this, mHandler);
                mChatService.start();
            }
            Toast.makeText(HavorBoardBLEControlActivity.this,"正在连接",Toast.LENGTH_SHORT).show();
            mChatService.connect(device);
        }
    };
  /*  BluetoothBLEChatService.OnStatusListener statusListener = new BluetoothBLEChatService.OnStatusListener(){
        @Override
        public void onChange(String name, boolean connected) {
            deviceName = name;
//            connectedStatu = connected;
            updateStatus(name,connectedStatu);
        }
    };*/
    private void updateStatus(String name, boolean connectedStatu) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bltStatus.setSelected(connectedStatu);
                if (connectedStatu){
                    bltStatus.setText(MessageFormat.format("蓝牙：已连接", name));
                }else {
                    bltStatus.setText("蓝牙：已断开");
                }

            }
        });
    }

    /**
     * 权限申请
     */
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION)!= PackageManager.PERMISSION_GRANTED){
            // 获取wifi连接需要定位权限,没有获取权限
            ActivityCompat.requestPermissions((Activity) this,new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_WIFI_STATE,
            },1);
        }
    }
    private void updateSpeedMsg() {
        if ((this.mChatService == null || this.mChatService.getState() != 3) ){
            return;
        }
        if (bean!=null&&leftRate!=null&&rightRate!=null){
            leftRate.setText(bean.getR()+"");
            rightRate.setText(bean.getL()+"");
            bean.setS(mState);
            Log.e("getPrintLTTTTLl","udate");
            if (this.mChatService == null || this.mChatService.getState() != 3){
                bltStatus.setSelected(false);
                bltStatus.setText("蓝牙：未连接");
                return;
            }
            sendMessage(new Gson().toJson(bean));
        }

    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void sendMessage(String message) {
        if (this.mBluetoothAdapter == null) {
            Toast.makeText(this, "手机无蓝牙设备", Toast.LENGTH_SHORT).show();
        } else if ((this.mChatService == null || this.mChatService.getState() != 3)) {
            Toast.makeText(this, (int) R.string.not_connected, Toast.LENGTH_SHORT).show();
        } else if (message.length() > 0) {

            mChatService.write(message.getBytes());

          /*  if (bluetoothBLEChatService!=null){
                bluetoothBLEChatService.sendMsg(message);
            }*/
        }
    }

}
